package com.IntelligentCommunity.algorithm.service.impl;

import com.IntelligentCommunity.algorithm.config.ComprefaceConfig;
import com.IntelligentCommunity.algorithm.domain.FaceImg;
import com.IntelligentCommunity.algorithm.domain.FaceImgResponse;
import com.IntelligentCommunity.algorithm.domain.FaceRecognitionConf;
import com.IntelligentCommunity.algorithm.domain.request.FaceAddRequest;
import com.IntelligentCommunity.algorithm.service.AlgorithmService;
import com.IntelligentCommunity.common.core.utils.file.Url2Base64;
import com.alibaba.fastjson2.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 美国五星上将麦克阿瑟
 */
@Service
public class AlgorithmServiceImpl implements AlgorithmService {

    @Autowired
    private ComprefaceConfig comprefaceConfig;

    private final RestTemplate restTemplate;

    // 构造方法 初始化
    public AlgorithmServiceImpl() {
        this.restTemplate = new RestTemplate();
    }

    @Override
    public Map<String, String> faceAdd(FaceAddRequest faceAddRequest) {

        Map<String, String> returnMap = new HashMap<String, String>();

        String imgs = faceAddRequest.getImg();

        String[] split = imgs.split(",");

        for (String img : split) {
            String base64 = Url2Base64.getBase64(img);

            String url = comprefaceConfig.recognitionUrl() + "faces?subject="+ faceAddRequest.getSubject();

            HttpHeaders httpHeaders = new HttpHeaders();

            httpHeaders.add("Content-Type", "application/json");
            if (faceAddRequest.getFlag() == 0) {
                httpHeaders.add("x-api-key", comprefaceConfig.getPopulationkey());
            }else {
                httpHeaders.add("x-api-key", comprefaceConfig.getDeploykey());
            }

            String requestBody = "{ \"file\": \""+base64+"\"}";

            HttpEntity<String> httpEntity = new HttpEntity<String>(requestBody, httpHeaders);

            ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

            String body = exchange.getBody();

            returnMap.putAll(JSON.parseObject(body, Map.class));
        }

        return returnMap;
    }

    @Override
    public Map<String, String> faceDel(String imageId) {
        String url = comprefaceConfig.recognitionUrl() + "faces/" + imageId;

        HttpHeaders httpHeaders = new HttpHeaders();

        httpHeaders.add("x-api-key", comprefaceConfig.getPopulationkey());

        HttpEntity<String> httpEntity = new HttpEntity<String>(httpHeaders);

        ResponseEntity<String> exchange = restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);

        String body = exchange.getBody();

        Map<String, String> map = JSON.parseObject(body, Map.class);

        return map;
    }

    @Override
    public Map<String, String> faceRec(FaceRecognitionConf faceRecognitionConf) {

        String base64 = Url2Base64.getBase64(faceRecognitionConf.getImg());

        String url = comprefaceConfig.recognitionUrl() + "recognize?face_plugins=landmarks&face_plugins=gender&face_plugins=age&face_plugins=pose";

        // 构建请求体
        String requestBody = "{ \"file\": \""+base64+"\"}";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");
        if (faceRecognitionConf.getFlag() == 0) {
            httpHeaders.add("x-api-key", comprefaceConfig.getPopulationkey());
        }else {
            httpHeaders.add("x-api-key", comprefaceConfig.getDeploykey());
        }

        HttpEntity<String> httpEntity = new HttpEntity<String>(requestBody, httpHeaders);

        // 发送POST请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

        String body = response.getBody();

        Map<String, String> map = JSON.parseObject(body, Map.class);

        return map;
    }



    @Override
    public FaceImgResponse faceFindBySubject(String subjectName) {


        String url = comprefaceConfig.recognitionUrl() + "faces?page=0&size=15&subject=" + subjectName;

        // 构建请求体
//        String requestBody = "{ \"file\": \""+faceRecognitionConf.getImg()+"\"}";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("x-api-key", comprefaceConfig.getPopulationkey());

        HttpEntity<String> httpEntity = new HttpEntity<String>(httpHeaders);

        // 发送POST请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, httpEntity, String.class);

        String bodyJSONString = response.getBody();

        Map<String, String> map = JSON.parseObject(bodyJSONString, Map.class);

        Object facesObj = map.get("faces");
        String faceJsonString = JSON.toJSONString(facesObj);

        List<FaceImg> faceImg = JSON.parseArray(faceJsonString, FaceImg.class);



        List<String> imgUrlList = new ArrayList<>();

        for (FaceImg img : faceImg) {
            String imgString = "";
            imgString = comprefaceConfig.getUrl()
                    + "api/v1/static/"
                    + comprefaceConfig.getPopulationkey()
                    + "/images/"
                    + img.getImage_id();
            imgUrlList.add(imgString);
        }

        FaceImgResponse faceImgResponse = new FaceImgResponse();

        faceImgResponse.setFaceImgList(imgUrlList);
        faceImgResponse.setXApiKey(comprefaceConfig.getPopulationkey());

        return faceImgResponse;
    }

    @Override
    public Map<String, String> faceDet(FaceRecognitionConf faceRecognitionConf) {

        String base64 = Url2Base64.getBase64(faceRecognitionConf.getImg());

        String url = comprefaceConfig.detectionUrl() + "detect?face_plugins=age,gender,mask&face_plugins=gender&face_plugins=age&face_plugins=pose";

        // 构建请求体
        String requestBody = "{ \"file\": \""+base64+"\"}";

        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("Content-Type", "application/json");
        httpHeaders.add("x-api-key", comprefaceConfig.getDetectionkey());

        HttpEntity<String> httpEntity = new HttpEntity<String>(requestBody, httpHeaders);

        // 发送POST请求
        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, String.class);

        String body = response.getBody();

        Map<String, String> map = JSON.parseObject(body, Map.class);

        return map;

    }

    @Override
    public void delBySubject(String subject) {

        try {
            String url = comprefaceConfig.recognitionUrl() + "subjects/" + subject;

            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.add("x-api-key", comprefaceConfig.getDeploykey());

            HttpEntity<String> httpEntity = new HttpEntity<String>(httpHeaders);

            // 发送POST请求
            restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
        }catch (Exception e){
            throw new RuntimeException("删除失败");
        }


    }

    @Override
    public Map<String, String> faceAddBath(List<FaceAddRequest> faceAddRequestList) {
        for (FaceAddRequest faceAddRequest : faceAddRequestList) {
            faceAdd(faceAddRequest);
        }
        return null;
    }

    @Override
    public void delBySubjects(List<String> subjects) {
        for (String subject : subjects) {
            try {
                String url = comprefaceConfig.recognitionUrl() + "subjects/" + subject;

                HttpHeaders httpHeaders = new HttpHeaders();
                httpHeaders.add("x-api-key", comprefaceConfig.getDeploykey());

                HttpEntity<String> httpEntity = new HttpEntity<String>(httpHeaders);

                // 发送POST请求
                restTemplate.exchange(url, HttpMethod.DELETE, httpEntity, String.class);
            }catch (Exception e){
                throw new RuntimeException("删除失败");
            }
        }
    }
}
